#include "util.hxx"

/* cmd parser*/
#include <iostream>
#include "clipp.hxx"
#include "minilog_static.hxx"
using namespace clipp;

int parseCarg(int argc, char *argv[],
              string& run_mode, string& cmd, string& set_value, string& address)
{
    string addr;
    auto appCli = (option("-m", "--mode") & value("run mode", run_mode),
                option("-c", "--module") & value("module cmd", cmd),
                option("-v", "--value") & value("cmd value", set_value),
                option("-a", "--address") & value("set ip:port", addr));
    if (!parse(argc, const_cast<char **>(argv), appCli)) {
        std::cerr << make_man_page(appCli, argv[0]) << std::endl;
        return 1;
    }
    if(addr != "")
        address = addr;

    return 0;
}

int _string_tailmatch(const std::string&self, const std::string&substr, int start, int end, int direction)
{
#define ADJUST_INDICES(start, end, len)     \
    if (end > len)                          \
        end = len;                          \
    else if (end < 0) {                     \
        end += len;                         \
        if (end < 0)                        \
        end = 0;                            \
    }                                       \
    if (start < 0) {                        \
        start += len;                       \
        if (start < 0)                      \
        start = 0;                          \
    }

    int selflen = (int)self.size();
    int slen = (int)substr.size();

    const char* str = self.c_str();
    const char* sub = substr.c_str();

    //对输入的范围进行校准
    ADJUST_INDICES(start, end, selflen);

    //字符串头部匹配（即startswith）
    if (direction < 0)
    {
        if (start + slen>selflen)
        return 0;
    }
    //字符串尾部匹配（即endswith）
    else
    {
        if (end - start<slen || start>selflen)
        return 0;
        if (end - slen > start)
            start = end - slen;
    }
    if (end - start >= slen)
        //mcmcmp函数用于比较buf1与buf2的前n个字节
        return !std::memcmp(str + start, sub, slen);
    return 0;

}

bool isStringStartsWith(const std::string&str, const std::string&suffix, int start, int end)
{
    //调用＿string＿tailmatch函数，参数-1表示字符串头部匹配
    int result = _string_tailmatch(str, suffix, start, end, -1);
    return static_cast<bool>(result);
}

bool isStringEndsWith(const std::string&str, const std::string&suffix, int start, int end)
{
    //调用＿string＿tailmatch函数，参数+1表示字符串尾部匹配
    int result = _string_tailmatch(str, suffix, start, end, +1);
    return static_cast<bool>(result);
}

